package com.company.cloud.admin.modules.admin.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.company.cloud.admin.modules.admin.controller.req.RoleSaveParam;
import com.company.cloud.admin.modules.admin.controller.req.RoleUpdateParam;
import com.company.cloud.admin.modules.cache.models.RoleModel;
import com.company.cloud.admin.modules.cache.utils.PTUserConvertUtils;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.constant.BaseReturnEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.admin.modules.admin.service.RoleMgrService;
import com.company.cloud.admin.modules.base.entity.RoleInfo;
import com.company.cloud.admin.modules.base.entity.RolePermissionInfo;
import com.company.cloud.admin.modules.base.entity.UserRoleInfo;
import com.company.cloud.admin.modules.base.service.RoleInfoService;
import com.company.cloud.admin.modules.base.service.RolePermissionInfoService;
import com.company.cloud.admin.modules.cache.service.UserPermissionCacheService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Authc
@RestController
@RequestMapping("/admin/role")
@Api(tags = "UserMgr_角色管理")
public class RoleMgrController {

    @Autowired
    private RoleInfoService roleInfoService;

    @Autowired
    private RoleMgrService roleMgrService;

    @Autowired
    private RolePermissionInfoService rolePermissionInfoService;

    @Autowired
    private UserPermissionCacheService userPermissionCacheService;

    @GetMapping("/list")
    @ApiOperation(value = "获取所属所有角色", response = RoleModel.class)
    public BaseResult list() {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        List<RoleInfo> roleList = roleInfoService.list(new QueryWrapper<RoleInfo>());
        List<RoleModel> data = new ArrayList<RoleModel>();
        if (!CollectionUtils.isEmpty(roleList)) {
            roleList.forEach(item -> {
                data.add(PTUserConvertUtils.getRoleModel(item));
            });
        }
        return BaseResult.ok(data);
    }

    @GetMapping("/get")
    @ApiOperation(value = "角色详情信息", response = RoleModel.class)
    public BaseResult get(@RequestParam("code") String code) {
        RoleInfo roleInfo = roleInfoService.getById(code);
        if (null == roleInfo) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        List<RolePermissionInfo> rolePerList = rolePermissionInfoService.list(
                new QueryWrapper<RolePermissionInfo>()
                        .eq("role_code", roleInfo.getCode())
        );
        RoleModel data = PTUserConvertUtils.getRoleModel(roleInfo, rolePerList);
        return BaseResult.ok(data);
    }

    @PostMapping("/save")
    @ApiOperation(value = "角色新增", response = BaseResult.class)
    @StaffLogc(title = "角色新增", action = "角色新增", actionAdo = "角色管理")
    public BaseResult save(@RequestBody RoleSaveParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        roleMgrService.save(params, userInfo);
        //重新初始化公司角色权限关系
        if (!CollectionUtils.isEmpty(params.getPermissionCodes())) {
            userPermissionCacheService.initPermissionRoleCache(userInfo.getCompanyNo());
        }
        return BaseResult.ok();
    }

    @PostMapping("/update")
    @ApiOperation(value = "角色修改", response = BaseResult.class)
    @StaffLogc(title = "角色修改", action = "角色修改", actionAdo = "角色管理")
    public BaseResult update(@RequestBody RoleUpdateParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        roleMgrService.update(params, userInfo);
        //重新初始化公司角色权限关系
        userPermissionCacheService.initPermissionRoleCache(userInfo.getCompanyNo());
        return BaseResult.ok();
    }

    @GetMapping("/delete")
    @ApiOperation(value = "角色删除", response = BaseResult.class)
    @StaffLogc(title = "角色删除", action = "角色删除", actionAdo = "角色管理")
    public BaseResult delete(@RequestParam("code") String code) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        List<UserRoleInfo> userRoleList = roleMgrService.delete(code, userInfo);
        //角色关联的用户退出
        if (!CollectionUtils.isEmpty(userRoleList)) {
            Set<Integer> userIds = new HashSet<Integer>();
            userRoleList.forEach(item -> {
                userIds.add(item.getUserId());
            });
            userPermissionCacheService.logoutUser(userIds);
        }
        //重新初始化公司角色权限关系
        userPermissionCacheService.initPermissionRoleCache(userInfo.getCompanyNo());
        return BaseResult.ok();
    }

}
